package com.mjk.common.core.drpc.filter;


import com.mjk.common.tools.gson.GsonUtils;
import com.mjk.common.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.apache.dubbo.rpc.service.GenericService;

import java.util.Date;
/**
 * dubbo 统一异常处理机制
 * @author mjk
 *
 */
@Slf4j
@Activate(group = {CommonConstants.CONSUMER}, order = -110000)
public class DubboExceptionFilter  implements Filter{
	
	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation)
			throws RpcException {
		Result result = null;
        try {
            result = invoker.invoke(invocation);
            if (result.hasException() && GenericService.class != invoker.getInterface()) {
                Throwable exception = result.getException();
                String data = String.format("[level]:Error，[createTime]:%s，[serviceName]:%s，[methodName]:%s，[inputParam]:%s",
                		TimeUtils.formatTime(new Date(), TimeUtils.DATE_FORMAT_DATETIME),invoker.getInterface().getName(), invocation.getMethodName(), GsonUtils.bean2Json(invocation.getArguments()));
                log.error(data, exception);                 
                result.setAttachment("code", "-99");
                return result;
            }
        } catch (RuntimeException e) {
            String data = String.format("[level]:Error，[createTime]:%s，[serviceName]:%s，[methodName]:%s，[inputParam]:%s",
            		   TimeUtils.formatTime(new Date(), TimeUtils.DATE_FORMAT_DATETIME),  invoker.getInterface().getName(), invocation.getMethodName(), GsonUtils.bean2Json(invocation.getArguments()));
            log.error(data, e);
        }
        return result;
	}

}
